import { defineStore } from 'pinia'
import router from '@/router'
import { ref } from "vue"


export const userRouterStore = defineStore('router', () => {
  const routerList = ref([])
  const setRouter = (arr) => {
    function compilerRouter(arr) {
      if (!arr) return
      routerList.value = arr
      arr.forEach(item => {
        let list = {
          name: item.name,
          path: item.path,
          meta: item.meta,
          component: item.component
        }
        if (item.children && item.children.length) {
          compilerRouter(item.children)
        }
        if (!item.children) {
          let path = loadComponent(item.component)
          list.component = path
          router.addRoute('menu', list)
        }

        // import.meta.glob 动态地导入多个模块
        function loadComponent(component) {
          let url = `../views/${component}.vue`
          let Module = import.meta.glob("../views/**/*.vue")
          return Module[url]
        }
      })
    }
    compilerRouter(arr)
  }

  const addRouter = () => {
    setRouter(routerList.value)
  }

  return {
    addRouter,
    routerList,
    setRouter,
  }

}, {
  persist: true
})